package top.gyq2019.utils;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.UUID;

/**
 * @author joy
 * @email 413735709@qq.com
 * @date 2021/12/27 10:18 上午
 */
public class PDFUtils {


    public final static String PATH = "/Users/raise/upload";
    /**
     * 生成pdf图片
     * @param dataMap 数据map
     * @param templateName 模板名称带ftl
     * @param dir 生成pdf的文件夹路径
     * @param filename 文件名称
     * @param basePdfPath 模板文件夹路径
     * @return
     */
    public static String convertFtlToPdf(Map<String, Object> dataMap,
                                   String templateName,
                                   String dir,
                                   String filename,
                                   String basePdfPath) throws IOException, TemplateException, DocumentException {
        String pdfPath = PATH + File.separator+dir;
        if (StringUtils.isEmpty(filename)) {
            filename= UUID.randomUUID().toString().replace("-","");
        }

        File f = new File(pdfPath);
        if (!f.exists()) {
            f.mkdirs();
        }

        String pdfFilePath = pdfPath + File.separator + filename + ".pdf";

        File fileImage = new File(pdfFilePath);
        if (fileImage.exists()) {
            fileImage.delete();
        }

        //创建配置实例
        Configuration configuration = new Configuration();

        //设置编码
        configuration.setDefaultEncoding("utf-8");

        //ftl模板文件
        configuration.setClassForTemplateLoading(PDFUtils.class,basePdfPath);

        //获取模板
        Template template = configuration.getTemplate(templateName);
        //将模板和数据模型合并生成文件
        Writer out = new StringWriter();
        //生成文件
        template.process(dataMap, out);

        //关闭流
        out.flush();
        out.close();

        // 获取生成文件的字符串
        String html=out.toString();
        Resource resource = new ClassPathResource("AlibabaPuHuiTi-3-85-Bold.ttf");
        InputStream inputStream = resource.getInputStream();

        String FONT=PATH+ File.separator+"AlibabaPuHuiTi-3-85-Bold.ttf";
        FileUtil.copyFile(inputStream, new File(FONT), StandardCopyOption.REPLACE_EXISTING);

        ITextRenderer render = new ITextRenderer();
        ITextFontResolver fontResolver = render.getFontResolver();
        // "AlibabaPuHuiTi-3-85-Bold" 自定义字体名称
        fontResolver.addFont(FONT,"AlibabaPuHuiTi-3-85-Bold", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED,null);
        // 解析html生成pdf
        render.setDocumentFromString(html);
        //解决图片相对路径的问题
        render.layout();

        FileOutputStream outStream = new FileOutputStream(pdfFilePath);
        render.createPDF(outStream);

        return pdfPath+File.separator+filename+".pdf";
    }


    /**
     * 生成pdf图片
     * @param dataMap 数据map
     * @param templateName 模板名称带ftl
     * @param dir 生成pdf的文件夹路径
     * @param filename 文件名称
     * @param basePdfPath 模板文件夹路径
     * @return
     */
    public static String convertFtlToImg(Map<String, Object> dataMap,
                                         String templateName,
                                         String dir,
                                         String filename,
                                         String basePdfPath) throws IOException, TemplateException, DocumentException {
        String pdfPath = PATH + File.separator+dir;
        if (StringUtils.isEmpty(filename)) {
            filename= UUID.randomUUID().toString().replace("-","");
        }

        File f = new File(pdfPath);
        if (!f.exists()) {
            f.mkdirs();
        }

        String pdfFilePath = pdfPath + File.separator + filename + ".png";

        File fileImage = new File(pdfFilePath);
        if (fileImage.exists()) {
            fileImage.delete();
        }

        //创建配置实例
        Configuration configuration = new Configuration();

        //设置编码
        configuration.setDefaultEncoding("utf-8");

        //ftl模板文件
        configuration.setClassForTemplateLoading(PDFUtils.class,basePdfPath);

        //获取模板
        Template template = configuration.getTemplate(templateName);
        //将模板和数据模型合并生成文件
        Writer out = new StringWriter();
        //生成文件
        template.process(dataMap, out);

        //关闭流
        out.flush();
        out.close();

        // 获取生成文件的字符串
        String html=out.toString();
        Resource resource = new ClassPathResource("font.ttf"); // 这个字体名称为 SimSun
        InputStream inputStream = resource.getInputStream();

        String FONT=PATH+ File.separator+"font.ttf";
        FileUtil.copyFile(inputStream, new File(FONT), StandardCopyOption.REPLACE_EXISTING);

        ITextRenderer render = new ITextRenderer();
        ITextFontResolver fontResolver = render.getFontResolver();
        fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 解析html生成pdf
        render.setDocumentFromString(html);
        //解决图片相对路径的问题
        render.layout();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//        FileOutputStream outStream = new FileOutputStream(new File(pdfFilePath));
        render.createPDF(outStream);

        final String IMAGE_TYPE = "png";
        PDDocument document = PDDocument.load(outStream.toByteArray());
        PDFRenderer renderer = new PDFRenderer(document);
//        BufferedImage bufferedImage = renderer.renderImage(0,2);
//        Image scaleImg = ImgUtil.cut(bufferedImage, new Rectangle(180, 100, 830, 280));

        BufferedImage bufferedImage = renderer.renderImage(0,4);

        FileOutputStream fileStream = new FileOutputStream(pdfFilePath);
        ImgUtil.write(bufferedImage,IMAGE_TYPE,fileStream);

        document.close();
        return dir+File.separator+filename+".png";
    }

}
